package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;

    /**
     * 自动补全
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            //准备request
            SearchRequest request = new SearchRequest("item");
            //准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            //请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //结果
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            ArrayList<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 结果过滤
     *
     * @param requestParams
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(RequestParams requestParams) {

        try {
            SearchRequest request = new SearchRequest("item");
            //query
            buildBasicQuery(requestParams, request);
            //排序
            if (!requestParams.getSortBy().equals("default")){
              request.source().sort(requestParams.getSortBy(), SortOrder.DESC);
            }
            //分页
            Integer page = requestParams.getPage();
            Integer size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 聚合过滤
     *
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(requestParams, request);
            request.source().size(0);
            buildAggregation(request);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            HashMap<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
           List<String> brandList = getAggByName(aggregations,"brandAgg");
           result.put("brand",brandList);
            List<String> categoryList = getAggByName(aggregations,"categoryAgg");
            result.put("category",categoryList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("item", id.toString());
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            Item item = itemClient.getItemById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            IndexRequest request = new IndexRequest("item").id(id.toString());
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms brandTerms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                                     .terms("brandAgg")
                                     .field("brand")
                                     .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
    }


    /**
     * 解析结果
     *
     * @param response
     * @return
     */
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        //获取响应
        SearchHits searchHits = response.getHits();
        //获取总条数
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            itemDocs.add(itemDoc);
        }
        PageDTO<ItemDoc> itemDocPageDTO = new PageDTO<>();
        itemDocPageDTO.setTotal(total);
        itemDocPageDTO.setList(itemDocs);
        return itemDocPageDTO;
    }

    /**
     * 条件
     *
     * @param requestParams
     * @param request
     */
    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字
        String key = requestParams.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //品牌
        if (requestParams.getBrand() != null && !"".equals(requestParams.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));
        }
        //分类
        if (requestParams.getCategory() != null && !"".equals(requestParams.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", requestParams.getCategory()));
        }
        //价格
        if (requestParams.getMinPrice() != null && requestParams.getMaxPrice() != null) {
            boolQuery.filter(
                    QueryBuilders.rangeQuery("price")
                            .gte(requestParams.getMinPrice())
                            .lte(requestParams.getMaxPrice())
            );
        }
        request.source().query(boolQuery);
    }
}
